/**
 *  Copyright 2009-2014 by WWW.KNET.CN  All rights reserved.
 */
package com.domain.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.domain.enums.TipEnum;
import com.domain.model.CloudWebMessage;
import com.domain.model.Dict;
import com.domain.model.Page;
import com.domain.model.Sysuser;
import com.domain.service.CloudWebMessageService;
import com.domain.service.DictService;
import com.domain.util.DateUtil;
import com.domain.util.commonUtil;

/**
 * TODO(这里用一句话描述这个类的作用)
 * 
 * @author liujie
 * @date 2015年4月17日 下午1:28:38
 * 
 */
@Controller
@RequestMapping("/message")
public class CloudWebMessageController extends SuperController {
	private static final Logger logger = LoggerFactory.getLogger(CloudWebMessageController.class);
	@Resource
	private CloudWebMessageService cloudWebMessageService;
	@Resource
	private DictService dictService;

	@RequestMapping("/index.html")
	public String index(HttpServletRequest request) {
		return "frame/index";
	}

	@RequestMapping("/list.html")
	public String getList(Page page, Integer type, String porCode, ModelMap model, HttpServletRequest request) {
		page = null == page ? new Page() : page;
		try {
			type = type == null ? type = 2 : type;
			Map<String, Object> paramMap = new HashMap<String, Object>();
			CloudWebMessage webMessage = new CloudWebMessage();
			webMessage.setPorCode(porCode);
			webMessage.setIfDelete(0l);
			paramMap.put(webMessage.key, webMessage);
			saveReqInfo(model, porCode, type);
			if (type == 1) { // 文本维护类型
				paramMap.put(PAGE_NAME, 1);
				paramMap.put(PAGESIZE_NAME, 1);
				List<CloudWebMessage> messageList = cloudWebMessageService.getListPage(paramMap);
				if (null != messageList && messageList.size() > 0) {
					webMessage = messageList.get(0);
				}
				model.addAttribute("entity", webMessage);
				return "message/editText";
			} else { // 列表维护类型
				paramMap.put(PAGE_NAME, page.getPage());
				paramMap.put(PAGESIZE_NAME, page.getPageSize());
				List<CloudWebMessage> messageList = cloudWebMessageService.getListPage(paramMap);
				Long total = cloudWebMessageService.getRows(paramMap);
				Page page2 = new Page(page.getPage(), page.getPageSize(), Integer.parseInt(total + ""));
				model.addAttribute("messageList", messageList);
				model.addAttribute("page", page2);
			}
			return "message/messageList";
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug(e.getMessage());
			return "exception";
		}
	}

	/***
	 * 首页滚动图片列表
	 * 
	 * @param request
	 * @param type
	 * @param porCode
	 * @param model
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "moveInfo.html", method = { RequestMethod.POST, RequestMethod.GET })
	public String moveInfo(HttpServletRequest request, Integer type, String porCode, ModelMap model,
			HttpServletResponse response) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		CloudWebMessage webMessage = new CloudWebMessage();
		webMessage.setPorCode(porCode);
		webMessage.setIfDelete(0l);
		paramMap.put(webMessage.key, webMessage);
		paramMap.put(PAGE_NAME, 1);
		paramMap.put(PAGESIZE_NAME, Integer.MAX_VALUE);
		List<CloudWebMessage> list = cloudWebMessageService.getListPage(paramMap);
		model.addAttribute("list", list);
		saveReqInfo(model, porCode, type);
		return "message/moveinfoList";
	}

	@RequestMapping(value = "/edit.html")
	public String edit(Integer type, ModelMap model, String porCode, CloudWebMessage cloudWebMessage,
			HttpServletRequest request) {
		saveReqInfo(model, porCode, type);
		if (null == cloudWebMessage || null == cloudWebMessage.getId()) {// add
			cloudWebMessage = new CloudWebMessage();
			cloudWebMessage.setPorCode(porCode);
		} else { // update
			CloudWebMessage msg = cloudWebMessageService.get(cloudWebMessage.getId());
			model.put("entity", msg);
		}
		if (type == 3) {
			return "message/msgFileEdit";
		} else if (type == 2) {
			return "message/moveinfoEdit";
		} else {
			return "message/messageEdit";
		}

	}
    //支持附件保存
	@RequestMapping(value = "/save.html", method = RequestMethod.POST)
	public String save(Integer type, ModelMap model, CloudWebMessage cloudWebMessage, HttpServletRequest request) {
		Sysuser user = getCurrentUser(request);
		MultipartHttpServletRequest mureq = (MultipartHttpServletRequest) request;
		MultipartFile file=mureq.getFile("file");
		try {
			Dict dict=dictService.getDictByCode("filePath");
			String prefixPath =(null !=dict && null !=dict.getDict_value() && !"".equals(dict.getDict_value()))?dict.getDict_value(): request.getServletContext().getRealPath("/");
			String savePath= commonUtil.getFilePath(prefixPath,file);//创建并返回路径;
			if (null == cloudWebMessage.getId()) {
				cloudWebMessage.setMesBy(user.getId());
				cloudWebMessage.setClick(0l);
				cloudWebMessage.setMesStatus(0l);
				cloudWebMessage.setMesAccessory(savePath);
				cloudWebMessageService.add(cloudWebMessage);
			} else {
					if (StringUtils.isNotBlank(savePath)) {
						cloudWebMessage.setMesAccessory(savePath);
					}
				cloudWebMessageService.update(cloudWebMessage);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("-------------保存带附件的信息异常：" + e.getMessage());
		}
		model.addAttribute("porCode", cloudWebMessage.getPorCode());
		model.addAttribute("type", type);
		if (type == 2) {
			return "redirect:/message/moveInfo.html";
		} else
			return "redirect:/message/list.html";
	}

	@RequestMapping(value = "/saveFile.html", method = RequestMethod.POST)
	public String saveFile(MultipartFile file, Integer type, ModelMap model, CloudWebMessage cloudWebMessage,
			HttpServletRequest request) {
		Sysuser user = getCurrentUser(request);
		try {
			if (null == cloudWebMessage.getId() && file.isEmpty()) {
				return "exception";
			}
			Dict dict = dictService.getDictByCode("filePath");
			String prefixPath = null != dict && null != dict.getDict_value() ? dict.getDict_value() : request
					.getServletContext().getRealPath("/");
			String suffixPath = DateUtil.dateFormat(new Date(), "yyyyMMdd") + "/";
			String path = prefixPath + suffixPath;
			String newFileName = "";
			if (file.getSize() > 0) {

				File tempPath = new File(prefixPath + suffixPath);
				if (!tempPath.exists()) {
					tempPath.mkdirs();
				}

				newFileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
				path = path + newFileName;
				File updateFile = new File(path);
				file.transferTo(updateFile);
			}

			if (null == cloudWebMessage.getId()) {
				cloudWebMessage.setMesBy(user.getId());
				cloudWebMessage.setClick(0l);
				cloudWebMessage.setMesAccessory(suffixPath + newFileName);
				cloudWebMessageService.add(cloudWebMessage);
			} else {
				if (StringUtils.isNotEmpty(newFileName)) {
					cloudWebMessage.setMesAccessory(suffixPath + newFileName);
				}
				cloudWebMessageService.update(cloudWebMessage);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("-------------保存带附件的信息异常：" + e.getMessage());
		}
		model.addAttribute("porCode", cloudWebMessage.getPorCode());
		model.addAttribute("type", type);
		return "redirect:/message/list.html";
	}

	@RequestMapping(value = "/saveText.html", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveText(Integer type, ModelMap model, CloudWebMessage cloudWebMessage,
			HttpServletRequest request) {
		Sysuser user = getCurrentUser(request);
		try {
			if (null == cloudWebMessage.getId()) {
				cloudWebMessage.setMesBy(user.getId());
				cloudWebMessageService.add(cloudWebMessage);
			} else {
				cloudWebMessageService.update(cloudWebMessage);
			}
			return TipEnum.getTipMap(TipEnum.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("-------------保存 只有文本信息异常：" + e.getMessage());
			return TipEnum.getTipMap(TipEnum.FAIL);
		}
	}

	@RequestMapping(value = "/delete.html", method = { RequestMethod.POST, RequestMethod.GET })
	// @ResponseBody
	public String delete(ModelMap model, CloudWebMessage cloudWebMessage, String porCode, Integer type,
			HttpServletRequest request) {
		Sysuser user = getCurrentUser(request);
		if (null == user) {
			return "";
		}
		try {
			cloudWebMessageService.deleteById(cloudWebMessage.getId());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("-------------删除webmessage:" + cloudWebMessage.getId() + ";异常：" + e.getMessage());
		}
		saveReqInfo(model, porCode, type);
		model.addAttribute("porCode", cloudWebMessage.getPorCode());
		if (type == 2) {
			return "redirect:/message/moveInfo.html";
		} else
			return "redirect:/message/list.html";
	}

	private void saveReqInfo(ModelMap model, String porCode, Integer type) {
		model.addAttribute(POR_CODE, porCode);
		model.addAttribute("type", type);
	}
}
